<template>
  <div class="page-container">
    <page_breadcrumb :getKeyMethod="init_table_model" @change="change_table_model" pageOption />

    <ex_super_table_page v-bind="option" ref="SuperTablePage" @selection-change="e => selection = e"
      @search="searchChange">
      <template v-slot:form_before="{ formData }">
        <el-form-item style="display: block;">
          <el-radio-group v-model="formData.status" @change="(e) => {
            formData.status = e
            $refs.SuperTablePage.loadDataForSearch()
          }">
            <el-radio-button label="">{{ $tt('label_all') }}</el-radio-button>
            <el-radio-button :label="item" v-for="(item, i) in $enumOptions['AbnormalStatusEnum']" :key="item">
              {{ $enumShow(item, 'AbnormalStatusEnum') }}
              {{ selectStatusCount[item] ? `(${selectStatusCount[item]})` : "(0)" }}</el-radio-button>
          </el-radio-group>
        </el-form-item>
      </template>
    </ex_super_table_page>
    <ex_super_dialog_form ref="acceptDialog" v-bind="accept_dialog"
      @afterSubmitSuccess="$refs['SuperTablePage'].reload()">
    </ex_super_dialog_form>
    <ex_super_dialog_form ref="disposeDialog" v-bind="dispose_dialog"
      @afterSubmitSuccess="$refs['SuperTablePage'].reload()">
    </ex_super_dialog_form>
    <ex_super_dialog_form ref="checkDialog" v-bind="check_dialog" @afterSubmitSuccess="$refs['SuperTablePage'].reload()">
    </ex_super_dialog_form>
    <anomaly_allot ref="anomaly_allot" @success="reload()" />
    <report_anomaly ref="report_anomaly" :orderTypeList="['INBOUND', 'OUTBOUND']" @success="reload()" />
  </div>
</template>
<script>
import business_function from "@/common/business_function"

import anomaly_allot from './dialog/anomaly_allot.vue'
import report_anomaly from '@/component/dialog/report_anomaly.vue'
import superTablePageFunction from '@/mixin/super-table-page-function';
import page_table_model_manage from '@/mixin/page_table_model_manage';
import emitOnFunction from '@/mixin/emit-on-function';
let emitKey = 'oms>anomaly_manage'
export default {
  title: 'label_abnormal_list',
  mixins: [superTablePageFunction, emitOnFunction(emitKey), page_table_model_manage,],
  components: { anomaly_allot, report_anomaly },
  data() {
    return {
      selection: [],
      selectStatusCount: {},
      option: {
        search: {
          default: { status: "", },
          model: [

            // { key: 'status', label: '异常状态', type: 'select', enum: 'AbnormalStatusEnum', },
            { key: "customerId", label: "label_customer", type: 'common_customer_choose' },
            { key: "code", label: "label_anomaly_code" },
            {key: 'orderNo', label: 'label_order_code' },
            { key: "reportUserId", label: "label_report_user", type: 'common_user_select' },
            {
              key: 'anomalySourceMode', label: 'label_generation_method', type:'select',enum:'AbnormalSourceModeEnum',
            },
            {
              key: 'startReportTime', label: 'label_start_report_time', type: 'date-picker',
              attrs: { type: "datetime", 'default-time': '00:00:00' },
            },

            {
              key: 'endReportTime', label: 'label_end_report_time', type: 'date-picker',
              attrs: { type: "datetime", 'default-time': '23:59:59' },
            },

          ],
        },
        actionExtra: [
          {
            label: 'label_report_exception', attrs: { icon: "el-icon-plus", type: 'primary' },
            auth:'oms_anomaly_report',
            click: () => {
              this['$refs']['report_anomaly'].showNew({

                formDisabled: false,
                onlySetData: true,
              })
            }
          },
          {
            label: "label_check_allocation", auth:'oms_anomaly_allot', click: () => {
              if (_.isEmpty(this.selection)) return this.$message.error(this.$tt('tip_please_select_order'))
              this.$refs.anomaly_allot.show(this.selection)
            }
          },
          {
            label: "label_anomaly_confirm", auth:'oms_anomaly_confirm', click: () => {
              if (_.isEmpty(this.selection)) return this.$message.error(this.$tt('tip_please_select_order'))

              this.anomalysConfirm(this.selection)
            }
          },
          {
            label: "label_anomaly_close", auth:'oms_anomaly_close', click: () => {
              if (_.isEmpty(this.selection)) return this.$message.error(this.$tt('tip_please_select_order'))
              this.anomalysClose(this.selection)
            }
          },
          {
            label: "label_anomaly_restart", auth:'oms_anomaly_restart', click: () => {
              if (_.isEmpty(this.selection)) return this.$message.error(this.$tt('tip_please_select_order'))

              this.anomalysRestart(this.selection)
            }
          },
          {
            label: "label_sync_customer_handler",auth:'oms_anomaly_sync', click: () => {
              if (_.isEmpty(this.selection)) return this.$message.error(this.$tt('tip_please_select_order'))
              this.anomalysSyncCustomer(this.selection)
            }
          },
          {
            label: 'label_export', click: this.exportExcel
          },
        ],
        table: {
          url: this.$url['oms/BaseAnomaly'],

          model: this.init_table_model(),
        }
      },


      accept_dialog: {
        customClass: 'dialog_auto',

        submitUrl: this.$url['oms/BaseAnomalyAccept'],
        detailUrl: this.$url['oms/BaseAnomalyDetail'],
        form: {
          itemClass: "form_item_default", inputClass: "form_input_default",
          formClass: "form_default_col2 flex_row_wrap",
          default: {},
          model: [
            { header: "label_base_info", },
            {
              key: "customerName", label: "label_customer", formType: 'text',
              formatter: (r, c, v, i) => this.$formatNameCode(v, r.customerCode)
            },
            {
              key: "orderType", label: "label_order_type", formType: 'text',
              formatter: (r, c, v, i) => this.$enumShow(v, "AbnormalOrderTypeEnum")
            },
            {
              key: "orderNo", label: "label_order_code", formType: 'text',
            },
            {
              key: "anomalyCause", label: "label_reason_abnormal", formType: 'text',
              formatter: (r, c, v, i) => this.$enumShow(v, "AnomalyCauseEnum")
            },
            {
              key: "anomalyClassifyName", label: "label_anomaly_class", formType: 'text',
            },
            {
              key: "anomalyDescribeName", label: "label_anomaly_desc", formType: 'text',
            },
            {
              key: "anomalyOccurrenceDate", label: "label_abnormal_happen_time", formType: 'text',
              formatter: (r, c, v, i) => this.$dateFormat(v)
            },
            { key: 'anomalyRemark', label: 'label_abnormal_remark', formType: 'text', },
            { key: 'anomalyBoxQty', label: 'label_abnormal_box_count', formType: 'text', },
            { key: 'anomalySkuQty', label: 'label_abnormal_piece_count', formType: 'text', },

            {
              key: 'reportUserName', label: 'label_report_user', formType: 'text',
              formatter: (r, c, v, i) => this.$formatNameCode(v, r.reportUserCode)
            },



            { key: 'anomalySkuValue', label: 'label_abnormal_sku_value', formType: 'text', },

            {
              key: 'attachedList', label: 'label_abnormal_attachment', type: 'upload-file',
              render: (h, { data }) => {
                return h('ex-upload-file', {
                  props: {
                    limit: 3,
                    disabled: true,
                    readonly: true,
                    value: data.attachedList
                  },
                },)
              }
            },
            { key: 'isAccept', label: 'label_is_accept', type: 'select', attrs: { enum: 'YesOrNoEnum' } },
            {
              key: 'acceptUserId', label: 'label_accept_user', type: 'common_user_select',
              keyExtra: { userCode: 'acceptUserCode', userName: 'acceptUserName' },
            },
          ],
          rules: {
            'isAccept': { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
            'acceptUserId': { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },

          },
        }
      },
      dispose_dialog: {
        customClass: 'dialog_auto',
        submitUrl: this.$url['oms/BaseAnomalyDispose'],
        submitDataHandle: (data) => {
          data.anomalyId = data.id
          data.anomalyCode = data.code
          return data
        },
        detailUrl: this.$url['oms/BaseAnomalyDetail'],
        detailDataHandle: (data) => {
          data.disposeBoxQty = data.anomalyBoxQty
          data.disposeSkuQty = data.anomalySkuQty
          return data
        },

        form: {
          itemClass: "form_item_default", inputClass: "form_input_default",
          formClass: "form_default_col2 flex_row_wrap",
          default: {},
          model: [
            { header: "label_base_info", },
            {
              key: "customerName", label: "label_customer", formType: 'text',
              formatter: (r, c, v, i) => this.$formatNameCode(v, r.customerCode)
            },
            {
              key: "orderType", label: "label_order_type", formType: 'text',
              formatter: (r, c, v, i) => this.$enumShow(v, "AbnormalOrderTypeEnum")

            },
            {
              key: "orderNo", label: "label_order_code", formType: 'text',
            },

            {
              key: "anomalyCause", label: "label_reason_abnormal", formType: 'text',
              formatter: (r, c, v, i) => this.$enumShow(v, "AnomalyCauseEnum")
            },
            {
              key: "anomalyClassifyName", label: "label_anomaly_class", formType: 'text',
            },
            {
              key: "anomalyDescribeName", label: "label_anomaly_desc", formType: 'text',
            },
            {
              key: "anomalyOccurrenceDate", label: "label_abnormal_happen_time", formType: 'text',
              formatter: (r, c, v, i) => this.$dateFormat(v)
            },
            { key: 'anomalyRemark', label: 'label_abnormal_remark', formType: 'text', },
            { key: 'anomalyBoxQty', label: 'label_abnormal_box_count', formType: 'text', },
            { key: 'anomalySkuQty', label: 'label_abnormal_piece_count', formType: 'text', },

            {
              key: 'reportUserName', label: 'label_report_user', formType: 'text',
              formatter: (r, c, v, i) => this.$formatNameCode(v, r.reportUserCode)
            },

            { key: 'anomalySkuValue', label: 'label_abnormal_sku_value', formType: 'text', },

            {
              key: 'attachedList', label: 'label_abnormal_attachment', type: 'upload-file',
              render: (h, { data }) => {
                return h('ex-upload-file', {
                  props: {
                    limit: 3,
                    disabled: true,
                    readonly: true,
                    value: data.attachedList
                  },
                },)
              }
            },
            { key: 'disposeResponsibleParty', label: 'label_handler_determine_responsible', type: 'select', attrs: { enum: 'AbnormalResponsiblePartyEnum' } },

            { key: 'disposeMode', label: 'label_do_with_method', type: 'select', attrs: { enum: 'AbnormalDisposeModeEnum' } },

            { key: 'disposeBoxQty', label: 'label_handler_box_count', },
            { key: 'disposeSkuQty', label: 'label_handler_piece_count', },
            { key: 'isCompensation', label: 'label_is_compensation', type: 'select', attrs: { enum: 'YesOrNoEnum' } },
            {
              key: 'compensationAmount', label: 'label_compensation_money', if: (data) => data.isCompensation == 'Y',
            },

          ],
          rules: {
            'disposeResponsibleParty': { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
            'disposeMode': { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
            'disposeBoxQty': {
              required: true, trigger: 'blur', validator: (r, v, cb) => {
                if (_.isEmpty(v)) {
                  cb(this.$tt('tip_can_no_empty'))
                } else if (!this.$reg.PureNumber(v)) {
                  cb(this.$tt("tip_only_positive_pure_decimal"))
                } else {
                  cb()
                }
              }
            },
            'disposeSkuQty': {
              required: true, trigger: 'blur', validator: (r, v, cb) => {
                if (_.isEmpty(v)) {
                  cb(this.$tt('tip_can_no_empty'))
                } else if (!this.$reg.PureNumber(v)) {
                  cb(this.$tt("tip_only_positive_pure_decimal"))
                } else {
                  cb()
                }
              }
            },

            'compensationAmount': {
              required: true, trigger: 'blur', validator: (r, v, cb) => {
                if (r.isCompensation == 'Y') {
                  cb()
                } else if (!this.$ruleStandard({ v, cb, type: "money", required: true, })) {
                  return
                } else {
                  cb()
                }
              }
            },
            'isCompensation': { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },

          },
        }
      },
      check_dialog: {
        customClass: 'dialog_auto',
        submitUrl: this.$url['oms/BaseAnomalyCheck'],
        detailUrl: this.$url['oms/BaseAnomalyDetail'],
        submitDataHandle: (data) => {
          data.anomalyId = data.id
          data.anomalyCode = data.code
          return data
        },
        form: {
          itemClass: "form_item_default", inputClass: "form_input_default",
          formClass: "form_default_col2 flex_row_wrap",
          default: {},
          model: [
            { header: "label_base_info", },
            {
              key: "customerName", label: "label_customer", formType: 'text',
              formatter: (r, c, v, i) => this.$formatNameCode(v, r.customerCode)
            },
            {
              key: "orderType", label: "label_order_type", formType: 'text',
              formatter: (r, c, v, i) => this.$enumShow(v, "AbnormalOrderTypeEnum")

            },
            {
              key: "orderNo", label: "label_order_code", formType: 'text',
            },

            {
              key: "anomalyCause", label: "label_reason_abnormal", formType: 'text',
              formatter: (r, c, v, i) => this.$enumShow(v, "AnomalyCauseEnum")
            },
            {
              key: "anomalyClassifyName", label: "label_anomaly_class", formType: 'text',
            },
            {
              key: "anomalyDescribeName", label: "label_anomaly_desc", formType: 'text',
            },
            {
              key: "anomalyOccurrenceDate", label: "label_abnormal_happen_time", formType: 'text',
              formatter: (r, c, v, i) => this.$dateFormat(v)
            },

            { key: 'anomalyRemark', label: 'label_abnormal_remark', formType: 'text', },
            { key: 'anomalyBoxQty', label: 'label_abnormal_box_count', formType: 'text', },
            { key: 'anomalySkuQty', label: 'label_abnormal_piece_count', formType: 'text', },

            {
              key: 'reportUserName', label: 'label_report_user', formType: 'text',
              formatter: (r, c, v, i) => this.$formatNameCode(v, r.reportUserCode)
            },
            { key: 'anomalySkuValue', label: 'label_abnormal_sku_value', formType: 'text', },
            {
              key: 'anomalyAttachedList', label: 'label_check_feedback_attachment', type: 'upload-file', attrs: { limit: 3 },
              render: (h, { data }) => {
                return h('ex-upload-file', {
                  props: {
                    limit: 3,
                    value: data.anomalyAttachedList
                  },
                  on: {
                    input: (list) => {
                      this.$set(data, 'anomalyAttachedList', list.map(it => {
                        it.type = 'CHECK'
                        return it
                      }))
                    }
                  }
                },)
              }
            },
            { key: 'checkResponsibleParty', label: 'label_check_determine_responsible', type: 'select', attrs: { enum: 'AbnormalResponsiblePartyEnum' } },
            {
              key: 'checkUserId', label: 'label_check_user', type: 'common_user_select',
              keyExtra: { userCode: 'checkUserCode', userName: 'checkUserName' },
            },
            {
              key: 'checkRemark', label: 'label_check_remarck',
            },
          ],
          rules: {
            'anomalyAttachedList': { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
            'checkResponsibleParty': { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
            'checkUserId': { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
            'checkRemark': { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
          },
        }
      },
    };
  },
  methods: {
    option_table_model() {
      return [
        { type: 'selection', clickToggle: true, keyGroup: 'label_table_operate' },

        { key: 'code', label: 'label_anomaly_code', 'min-width': 200, 'show-overflow-tooltip': true, },
        { key: 'anomalyClassifyName', label: 'label_anomaly_class', 'min-width': 160, 'show-overflow-tooltip': true, },

        { key: 'anomalyDescribeName', label: 'label_anomaly_desc', 'min-width': 160, 'show-overflow-tooltip': true, },
        {
          key: 'orderType', label: 'label_order_type', 'min-width': 160, 'show-overflow-tooltip': true,
          formatter: (r, c, v, i) => this.$enumShow(v, "AbnormalOrderTypeEnum")
        },
        {
          key: 'orderNo', label: 'label_order_code', 'min-width': 160, 'show-overflow-tooltip': true,
        },
        {
          key: 'businessOrderNo', label: 'label_business_order_code', 'min-width': 160, 'show-overflow-tooltip': true,
        },
        { key: 'customerName', label: 'label_customer_name', 'width': 100, 'show-overflow-tooltip': true, },
        { key: 'customerCode', label: 'label_customer_code', 'width': 100, 'show-overflow-tooltip': true, },
        {
          key: 'anomalySourceSystem', label: 'label_generation_system', 'width': 100, 'show-overflow-tooltip': true,
          formatter: (r, c, v, i) => this.$enumShow(v, "AbnormalSourceSystemEnum")
        },
        {
          key: 'anomalySourceMode', label: 'label_generation_method', 'width': 100, 'show-overflow-tooltip': true,
          formatter: (r, c, v, i) => this.$enumShow(v, "AbnormalSourceModeEnum")
        },
        {
          key: 'status', label: 'label_status', 'width': 100, 'show-overflow-tooltip': true,
          formatter: (r, c, v, i) => this.$enumShow(v, "AbnormalStatusEnum")
        },
        {
          type: 'operate', width: 160, fixed: 'right', operate: [
            {
              label: 'label_edit',
              auth:'oms_anomaly_edit',
              if: (row) => ['WAIT_ACCEPTED'].includes(row.status) , click: (row) => {
                this['$refs']['report_anomaly'].showNew({
                  formDisabled: true,
                  submitUrl: this.$url['oms/BaseAnomalyEdit'],
                  params: { "id": row["id"] },
                })
              }
            },
            {
              type: 'more',
              items: [
                {
                  label: 'label_view_detail', click: (row) => {
                    this.$router.push({
                      path: '/page/oms/anomaly/anomaly_detail', query: { id: row.id, }
                    })
                  }
                },
                {
                  label: 'label_abnormal_accept',
                  auth:'oms_anomaly_accept',
                  click: (row) => {
                    this['$refs']['acceptDialog'].show({ "id": row["id"] }, {}, this.$tt('label_abnormal_accept'))
                  }
                },
                {
                  label: 'label_check_feedback', auth:'oms_anomaly_check', click: (row) => {
                    this['$refs']['checkDialog'].show({ "id": row["id"] }, {}, this.$tt('label_check_feedback'))
                  }
                },
                {
                  label: 'label_exception_handle', auth:'oms_anomaly_dispose', click: (row) => {
                    this['$refs']['disposeDialog'].show({ "id": row["id"] }, {}, this.$tt('label_exception_handle'))
                  }
                },
                {
                  label: 'label_sync_customer_handler', auth:'oms_anomaly_sync', click: (row) => this.anomalysSyncCustomer([row])
                },
              ]
            }
          ]
        }
      ]
    },
    searchChange(data) {
      this.$ajax({
        url: this.$url['oms/BaseAnomalyStatusCount'],
        method: 'post',
        data: data,
        success: (res) => {
          if (res && res.data && res.data.rows) {
            const countMap = {}
            res.data.rows.forEach(it => {
              countMap[it.status] = it.count
            })
            this.selectStatusCount = countMap
          }

        }
      })
    },
    anomalysSyncCustomer(rows) {
      this.$confirm(this.$tt('tip_xxx_will_comfirm_count_sync_customer_abnormal', { count: rows.length }), this.$tt('label_tip'), {
        type: 'warning'
      }).then(() => {
        this.$ajax({
          url: this.$url['oms/BaseAnomalySync'],
          method: 'post', type: "json",
          loading: true,
          data: {
            anomalySyncParamList: rows.map(it => {
              return {
                anomalyId: it.id,
                anomalyCode: it.code,
              }
            })
          },
          success: (res) => {
            this.$message({
              showClose: true,
              message: this.$tt('tip_submit_success'),
              type: 'success'
            })
            this.reload()
          }
        })
      }).catch(() => {
      });

    },

    anomalysConfirm(rows) {
      this.$confirm(this.$tt('tip_xxx_will_comfirm_count_abnormal', { count: rows.length }), this.$tt('label_tip'), {
        type: 'warning'
      }).then(() => {
        this.$ajax({
          url: this.$url['oms/BaseAnomalyConfirm'],
          method: 'post', type: "json",
          loading: true,
          data: {
            anomalyConfirmParamList: rows.map(it => {
              return {
                anomalyId: it.id,
                anomalyCode: it.code,
              }
            })
          },
          success: (res) => {
            this.$message({
              showClose: true,
              message: this.$tt('tip_submit_success'),
              type: 'success'
            })
            this.reload()
          }
        })
      }).catch(() => {
      });

    },
    anomalysClose(rows) {
      this.$confirm(this.$tt('tip_xxx_will_close_count_abnormal', { count: rows.length }), this.$tt('label_tip'), {
        type: 'warning'
      }).then(() => {
        this.$ajax({
          url: this.$url['oms/BaseAnomalyClose'],
          method: 'post', type: "json",
          loading: true,
          data: {
            anomalyCloseList: rows.map(it => {
              return {
                anomalyId: it.id,
                anomalyCode: it.code,
              }
            })
          },
          success: (res) => {
            this.$message({
              showClose: true,
              message: this.$tt('tip_submit_success'),
              type: 'success'
            })
            this.reload()
          }
        })
      }).catch(() => {
      });
    },

    anomalysRestart(rows) {
      this.$confirm(this.$tt('tip_xxx_will_restart_count_abnormal', { count: rows.length }), this.$tt('label_tip'), {
        type: 'warning'
      }).then(() => {
        this.$ajax({
          url: this.$url['oms/BaseAnomalyRestart'],
          method: 'post', type: "json",
          loading: true,
          data: {
            anomalyRestartList: rows.map(it => {
              return {
                anomalyId: it.id,
                anomalyCode: it.code,
              }
            })

          },
          success: (res) => {
            this.$message({
              showClose: true,
              message: this.$tt('tip_submit_success'),
              type: 'success'
            })
            this.reload()
          }
        })
      }).catch(() => {
      });

    },

    exportExcel() {

      business_function.confirmOperateBaseSelectOrForm.call(this, {
        data: this.$refs.SuperTablePage.getSearchFormData(),
        model: this.option.search.model,
        selection: this.selection,
        callback: (selection, data) => {
          let params = {}
          if (!_.isEmpty(selection)) {
            params = {
              ids: selection.map(it => it.id)
            }
          } else {
            params = data
          }
          this.$functionCommon({
            url: this.$url['oms/BaseAnomalyExport'],
            data: params, type: 'form',
          })
        }
      })

    },
  }
};

</script>
<style></style>
